getToken();
let user = JSON.parse(window.localStorage.getItem("userInfo"));
let token = window.localStorage.getItem("token");
const payTypesArr = ["zfb", "wx", "yhk"];

const payInfoObj = {};
const initPayTypesIdAndImgUrl = () => {
  payTypesArr.forEach((type) => {
    payInfoObj[type] = {
      id: null,
      imgUrl: null,
    };
  });
};

initPayTypesIdAndImgUrl();

const payTypeStrObj = {
  WX_STR: "微信",
  ZFB_STR: "支付宝",
  YHK_STR: "银行卡",
};
if (user) {
  // 回显已存在的用户信息
  $("#nickname").val(user.name);
  $("#zname").val(user.zname);
  $("#mobile").val(user.mobile);
  $.ajax({
    url: `${server}v1/api/blance/site/${user.id}`,
    dataType: "json",
    type: "GET",
    processData: false,
    headers: { token: token },
    success: function (res) {
      const { data, code } = res;
      if (code == 200) {
        const { WX_STR, ZFB_STR, YHK_STR } = payTypeStrObj;
        // let zfbCode =
        //   data && data.length > 0 ? data.map((item) => item.payName) : [];
        // let imgList =
        //   data && data.length > 0 ? data.map((item) => item.pay) : [];
        if (data && Array.isArray(data) && data.length > 0) {
          data.forEach((i) => {
            const { id, pay } = i;
            switch (i.type.display) {
              case "支付宝":
                payInfoObj.zfb.id = id;
                payInfoObj.zfb.imgUrl = pay;
                break;
              case "微信":
                payInfoObj.wx.id = id;
                payInfoObj.wx.imgUrl = pay;
                break;
              default:
                payInfoObj.yhk.id = id;
                payInfoObj.yhk.imgUrl = pay;
                return;
            }
          });
        }
        // payInfo = imgList[0];
        // let img = `<em><img src="${server}${imgList[0]}" class="code-img" /><i class="del" type="zfb">&times;</i></em>`;
        // if (img) {
        //   $("#add_zfb_img").hide();
        // } else {
        //   $("#add_zfb_img").show();
        // }
        // $("#imgList").append(img);
        // $("#zfb").val(zfbCode[0]);
        const zfbPayObj = data.find((i) => i.type.display === ZFB_STR);
        const wxPayObj = data.find((i) => i.type.display === WX_STR);
        const bankPayObj = data.find((i) => i.type.display === YHK_STR);
        if (zfbPayObj) {
          if (zfbPayObj.pay) {
            const zfbPayImg = `<em><img src="${zfbPayObj.pay}" class="code-img" /><i class="del" type="zfb">&times;</i></em>`;
            $("#imgList").append(zfbPayImg);
            $("#add_zfb_img").hide();
          }
          $("#zfb").val(zfbPayObj.payName);
        }
        if (wxPayObj) {
          if (wxPayObj.pay) {
            const wxPayImg = `<em><img src="${wxPayObj.pay}" class="code-img" /><i class="del" type="wx">&times;</i></em>`;
            $("#wx_img_list").append(wxPayImg);
            $("#add_wx_img").hide();
          }
          $("#wx").val(wxPayObj.payName);
        }
        if (bankPayObj) {
          if (bankPayObj.pay) {
            const bankPayImg = `<em><img src="${bankPayObj.pay}" class="code-img" /><i class="del" type="yhk">&times;</i></em>`;
            $("#yhk_img_list").append(bankPayImg);
            $("#add_yhk_img").hide();
          }
          $("#yhk").val(bankPayObj.payName);
        }
      } else {
        mui.alert(res.msg);
      }
    },
    error: function (err) {
      mui.alert("未授权");
    },
  });

  function setSaveBtnDisabledState(isDisable) {
    $("#subPay").attr("disabled", isDisable);
  }

  function startRead(type) {
    var fileDom = document.getElementById(`img_up_file_${type}`);
    var img = document.getElementById(`img_content_img_${type}`);
    if (fileDom && img) {
      fileHandle(fileDom, img, type);
    }
  }

  function fileHandle(fileDom, img, type) {
    let codeStr = randomString(8);
    var file = fileDom.files[0];
    var formFile = new FormData();
    formFile.append("file", file);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    // reader.onloadstart = function (e) {
    //   setSaveBtnDisabledState(true);
    // try {
    //   if (fetch) {
    //     fetch(`${server}v1/img/upload?project=${codeStr}`, {
    //       method: "post",
    //       body: formFile,
    //       headers: new Headers({
    //         // "Content-Type": "application/x-www-form-urlencoded;charset=utf-8 ",
    //         token,
    //         Origin: "*",
    //       }),
    //     })
    //       .then((res) => res.json())
    //       .then((data) => {
    //         if (data.code == 200) {
    //           payInfoObj[type].imgUrl = data.data.data.src;
    //           $("#pay").val(data.data.data.src);
    //         } else {
    //           mui.alert(data.msg);
    //         }
    //         setSaveBtnDisabledState(false);
    //       })
    //       .catch((err) => {
    //         console.log(err);
    //         mui.alert("服务器出了点小问题，请稍后重试");
    //       });
    //   } else {
    //   $.ajax({
    //     url: `${server}v1/img/upload?project=${codeStr}`,
    //     data: formFile,
    //     dataType: "json",
    //     type: "post",
    //     processData: false, // 使用formData传参很重要的配置
    //     contentType: false, // 使用formData传参很重要的配置
    //     headers: {
    //       "Content-Type": "application/x-www-form-urlencoded",
    //       token: token,
    //     },
    //     success: function (res) {
    //       if (res.code == 200) {
    //         payInfoObj[type].imgUrl = res.data.data.src;
    //         $("#pay").val(res.data.data.src);
    //       } else {
    //         mui.alert(res.msg);
    //       }
    //       setSaveBtnDisabledState(false);
    //     },
    //     error: function (err) {
    //       mui.alert("服务器出了点小问题，请稍后重试");
    //     },
    //   });
    // }
    //   } catch (err) {
    //     alert(JSON.stringify(err));
    //   }
    // };
    reader.onload = function (e) {
      var param = {
        keyst: codeStr,
        val: reader.result.split('base64,')[1],
      }
      $.ajax({
        url: `${server}/v1/api/diction`,
        data: JSON.stringify(param),
        dataType: "json",
        type: "post",
        headers: {
          "Accept": "application/json",
          "Content-Type": "application/json",
          token: token
        },
        processData: false,
        success: function (res) {
          console.log(res);
          if (res.code == 200) {
            const uurl = 'https://sdqn5b.cn:449/v1/img/getImg?project=' + codeStr;
            payInfoObj[type].imgUrl = uurl;
            $("#pay").val(uurl);
          } else {
            mui.alert(res.msg);
          }
          setSaveBtnDisabledState(false);
        },
        error: function (err) {
          mui.alert("服务器出了点小问题，请稍后重试");
        },
      });
      img.setAttribute("src", reader.result);
    };
  }

  function randomString(e) {
    e = e || 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
      a = t.length,
      n = "";
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n;
  }

  $("#subPay").click(function () {
    // 编辑收款信息
    const userSite = [];
    payTypesArr.forEach((i) => {
      const payTypeObj = {
        payName: $(`#${i}`).val(),
        pay: payInfoObj[i].imgUrl,
        type: i.toLocaleUpperCase(),
        userId: user.id,
        id: payInfoObj[i].id,
      };
      userSite.push(payTypeObj);
    });
    $.ajax({
      url: `${server}v1/api/blance/site`,
      data: JSON.stringify(userSite),
      dataType: "json",
      type: "post",
      processData: false,
      headers: { "Content-Type": "application/json", token: token },
      success: function (res) {
        if (res.code == 200) {
          mui.alert("添加成功!");
          setTimeout(() => {
            location.href = "memberCenter.html";
          }, 1000);
        } else {
          mui.alert(res.msg);
        }
      },
      error: function (err) {
        mui.alert("服务器出了点小问题，请稍后重试");
      },
    });
  });
} else {
  mui.alert("您还未登录，请先登录");
}

$("#imgList,#wx_img_list,#yhk_img_list").on("click", ".del", function () {
  $(this).parent("em").hide();
  const type = $(this).attr("type");
  type === "zfb" && $("#add_zfb_img").show();
  type === "wx" && $("#add_wx_img").show();
  type === "yhk" && $("#add_yhk_img").show();
  // 删除数组里的已上传图片地址
});
